<template>
  <div class="order-dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
              <el-icon :size="40"><DocumentCopy /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.totalOrders }}</div>
              <div class="stat-label">总订单数</div>
            </div>
          </div>
          <div class="stat-trend">
            <span :class="['trend-text', statistics.ordersTrend > 0 ? 'trend-up' : 'trend-down']">
              <el-icon><CaretTop v-if="statistics.ordersTrend > 0" /><CaretBottom v-else /></el-icon>
              {{ Math.abs(statistics.ordersTrend) }}%
            </span>
            <span class="trend-label">较上月</span>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
              <el-icon :size="40"><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ formatNumber(statistics.totalAmount) }}</div>
              <div class="stat-label">订单总额</div>
            </div>
          </div>
          <div class="stat-trend">
            <span :class="['trend-text', statistics.amountTrend > 0 ? 'trend-up' : 'trend-down']">
              <el-icon><CaretTop v-if="statistics.amountTrend > 0" /><CaretBottom v-else /></el-icon>
              {{ Math.abs(statistics.amountTrend) }}%
            </span>
            <span class="trend-label">较上月</span>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
              <el-icon :size="40"><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.pendingOrders }}</div>
              <div class="stat-label">待处理订单</div>
            </div>
          </div>
          <div class="stat-trend">
            <el-button type="primary" size="small" text @click="handlePendingOrders">
              立即处理
            </el-button>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
              <el-icon :size="40"><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.completionRate }}%</div>
              <div class="stat-label">订单完成率</div>
            </div>
          </div>
          <div class="stat-trend">
            <el-progress 
              :percentage="statistics.completionRate" 
              :stroke-width="6" 
              :show-text="false"
              color="#43e97b"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>订单趋势分析</span>
              <el-radio-group v-model="trendPeriod" size="small" @change="loadTrendData">
                <el-radio-button label="week">近7天</el-radio-button>
                <el-radio-button label="month">近30天</el-radio-button>
                <el-radio-button label="year">近12月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card>
          <template #header>
            <span>订单状态分布</span>
          </template>
          <div ref="statusChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>TOP10 热销商品</span>
          </template>
          <div ref="topProductsChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <template #header>
            <span>TOP10 客户排行</span>
          </template>
          <div ref="topCustomersChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最新订单 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>最新订单</span>
              <el-button type="primary" size="small" @click="goToOrders">
                查看全部
                <el-icon><ArrowRight /></el-icon>
              </el-button>
            </div>
          </template>
          <el-table :data="recentOrders" stripe>
            <el-table-column prop="orderNo" label="订单号" width="150" />
            <el-table-column prop="customerName" label="客户" width="150" />
            <el-table-column prop="totalAmount" label="订单金额" width="120">
              <template #default="{ row }">
                ¥{{ row.totalAmount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column prop="salesman" label="销售员" width="100" />
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button type="primary" size="small" text @click="handleViewOrder(row)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { 
  DocumentCopy, 
  Money, 
  Clock, 
  TrendCharts,
  CaretTop,
  CaretBottom,
  ArrowRight
} from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const trendPeriod = ref('week')
const trendChartRef = ref(null)
const statusChartRef = ref(null)
const topProductsChartRef = ref(null)
const topCustomersChartRef = ref(null)

let trendChart = null
let statusChart = null
let topProductsChart = null
let topCustomersChart = null

// 统计数据
const statistics = reactive({
  totalOrders: 1248,
  ordersTrend: 12.5,
  totalAmount: 3856240,
  amountTrend: 8.3,
  pendingOrders: 23,
  completionRate: 92
})

// 最新订单
const recentOrders = ref([
  {
    id: 1,
    orderNo: 'SO20240115001',
    customerName: '张三',
    totalAmount: 15000,
    status: '已完成',
    createTime: '2024-01-15 10:00:00',
    salesman: '销售员A'
  },
  {
    id: 2,
    orderNo: 'SO20240115002',
    customerName: '北京科技有限公司',
    totalAmount: 8500,
    status: '待发货',
    createTime: '2024-01-15 14:00:00',
    salesman: '销售员B'
  },
  {
    id: 3,
    orderNo: 'SO20240115003',
    customerName: '王总',
    totalAmount: 25000,
    status: '待审批',
    createTime: '2024-01-15 16:00:00',
    salesman: '销售员C'
  },
  {
    id: 4,
    orderNo: 'SO20240115004',
    customerName: '李四',
    totalAmount: 12000,
    status: '已确认',
    createTime: '2024-01-15 17:00:00',
    salesman: '销售员A'
  },
  {
    id: 5,
    orderNo: 'SO20240115005',
    customerName: '上海贸易公司',
    totalAmount: 35000,
    status: '已发货',
    createTime: '2024-01-15 18:00:00',
    salesman: '销售员D'
  }
])

// 方法
const formatNumber = (num) => {
  return (num / 10000).toFixed(2) + '万'
}

const getStatusType = (status) => {
  const statusMap = {
    '待确认': 'warning',
    '待审批': 'warning',
    '已确认': 'primary',
    '待发货': 'info',
    '已发货': 'success',
    '已完成': 'success',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

const handlePendingOrders = () => {
  router.push('/sales/orders?status=pending')
}

const goToOrders = () => {
  router.push('/sales/orders')
}

const handleViewOrder = (row) => {
  router.push(`/sales/orders/${row.id}`)
}

// 加载趋势数据
const loadTrendData = () => {
  const data = {
    week: {
      dates: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      orders: [120, 132, 101, 134, 90, 230, 210],
      amount: [15000, 18500, 12000, 20000, 13500, 28000, 25000]
    },
    month: {
      dates: Array.from({ length: 30 }, (_, i) => `${i + 1}日`),
      orders: Array.from({ length: 30 }, () => Math.floor(Math.random() * 150) + 80),
      amount: Array.from({ length: 30 }, () => Math.floor(Math.random() * 20000) + 10000)
    },
    year: {
      dates: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      orders: [3520, 3200, 3800, 4200, 3900, 4500, 4800, 4600, 5000, 5200, 4900, 5500],
      amount: [420000, 380000, 450000, 520000, 480000, 560000, 600000, 580000, 640000, 680000, 620000, 720000]
    }
  }

  const periodData = data[trendPeriod.value]
  
  if (trendChart) {
    trendChart.setOption({
      xAxis: {
        data: periodData.dates
      },
      series: [
        { data: periodData.orders },
        { data: periodData.amount }
      ]
    })
  }
}

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) return
  
  trendChart = echarts.init(trendChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['订单数', '订单金额']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: []
    },
    yAxis: [
      {
        type: 'value',
        name: '订单数',
        position: 'left'
      },
      {
        type: 'value',
        name: '金额(元)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '订单数',
        type: 'line',
        smooth: true,
        data: [],
        itemStyle: {
          color: '#667eea'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(102, 126, 234, 0.5)' },
            { offset: 1, color: 'rgba(102, 126, 234, 0.1)' }
          ])
        }
      },
      {
        name: '订单金额',
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        data: [],
        itemStyle: {
          color: '#f5576c'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(245, 87, 108, 0.5)' },
            { offset: 1, color: 'rgba(245, 87, 108, 0.1)' }
          ])
        }
      }
    ]
  }
  
  trendChart.setOption(option)
  loadTrendData()
}

// 初始化状态分布图表
const initStatusChart = () => {
  if (!statusChartRef.value) return
  
  statusChart = echarts.init(statusChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 450, name: '已完成', itemStyle: { color: '#43e97b' } },
          { value: 280, name: '待发货', itemStyle: { color: '#4facfe' } },
          { value: 180, name: '已确认', itemStyle: { color: '#667eea' } },
          { value: 120, name: '待审批', itemStyle: { color: '#f5576c' } },
          { value: 80, name: '待确认', itemStyle: { color: '#fa709a' } }
        ]
      }
    ]
  }
  
  statusChart.setOption(option)
}

// 初始化热销商品图表
const initTopProductsChart = () => {
  if (!topProductsChartRef.value) return
  
  topProductsChart = echarts.init(topProductsChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    yAxis: {
      type: 'category',
      data: ['商品J', '商品I', '商品H', '商品G', '商品F', '商品E', '商品D', '商品C', '商品B', '商品A']
    },
    series: [
      {
        type: 'bar',
        data: [1200, 1450, 1680, 1820, 2050, 2280, 2450, 2680, 2920, 3150],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#667eea' },
            { offset: 1, color: '#764ba2' }
          ])
        },
        barWidth: '60%'
      }
    ]
  }
  
  topProductsChart.setOption(option)
}

// 初始化客户排行图表
const initTopCustomersChart = () => {
  if (!topCustomersChartRef.value) return
  
  topCustomersChart = echarts.init(topCustomersChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    yAxis: {
      type: 'category',
      data: ['客户J', '客户I', '客户H', '客户G', '客户F', '客户E', '客户D', '客户C', '客户B', '客户A']
    },
    series: [
      {
        type: 'bar',
        data: [85000, 92000, 98000, 105000, 112000, 125000, 138000, 152000, 168000, 185000],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#4facfe' },
            { offset: 1, color: '#00f2fe' }
          ])
        },
        barWidth: '60%'
      }
    ]
  }
  
  topCustomersChart.setOption(option)
}

// 窗口大小改变时重绘图表
const handleResize = () => {
  trendChart?.resize()
  statusChart?.resize()
  topProductsChart?.resize()
  topCustomersChart?.resize()
}

// 生命周期
onMounted(() => {
  setTimeout(() => {
    initTrendChart()
    initStatusChart()
    initTopProductsChart()
    initTopCustomersChart()
    window.addEventListener('resize', handleResize)
  }, 100)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
  statusChart?.dispose()
  topProductsChart?.dispose()
  topCustomersChart?.dispose()
})
</script>

<style scoped>
.order-dashboard {
  padding: 20px;
  background: #f0f2f5;
  min-height: 100vh;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-trend {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.trend-text {
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 4px;
}

.trend-up {
  color: #67c23a;
}

.trend-down {
  color: #f56c6c;
}

.trend-label {
  font-size: 12px;
  color: #909399;
}

.charts-row {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: 350px;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  font-weight: 600;
  color: #303133;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style>

